package controller

import (
	base "nonius/base/controllers"
	"nonius/forms"
	"nonius/services"
	"nonius/tools"

	"github.com/astaxie/beego/context"
)

type LinkController struct {
	base.RequiredAuthController
}

func (c *LinkController) Search() {
	if c.Ctx.Input.IsPost() {
		var s string
		c.Ctx.Input.Bind(&s, "search")
		c.Data["links"] = services.SearchLink(s)
		c.TplName = "link/link.html"
	}
}

func (c *LinkController) Edit() {

	if c.Ctx.Input.IsPost() {
		var form forms.LinkForm
		c.ParseForm(&form)
		services.UpdateLink(form.ID, c.Ctx.Input.Host(), form.Longlink)
		c.Redirect("/link/query", 302)
		return
	}
	var id int64
	c.Ctx.Input.Bind(&id, "id")
	c.Data["id"] = id
	c.Data["links"] = services.GetLink(id)
	c.TplName = "link/edit.html"
	// c.Redirect("/link/query", 302)
}

func (c *LinkController) Delete() {
	var id int64
	c.Ctx.Input.Bind(&id, "id")
	services.DelLink(id)
	c.Redirect("/link/query", 302)

}

func (c *LinkController) Query() {
	if c.Ctx.Input.IsGet() {
		c.Data["links"] = services.GetLinks()
		c.TplName = "link/link.html"
	}
}

func (c *LinkController) Add() {
	if c.Ctx.Input.IsGet() {
		c.TplName = "link/add.html"
		return
	} else if c.Ctx.Input.IsPost() {
		var form forms.LinkForm
		c.ParseForm(&form)
		slink := tools.CreateRandomString(6)
		services.AddLink(c.Ctx.Input.Host(), slink, form.Longlink)
		c.Redirect("/link/query", 302)
		return
	}
	c.Redirect("/link/query", 302)

}

func RedirectLongLink(c *context.Context) {
	slink := c.Input.Param(":link")
	if len(slink) > 6 {
		return
	}
	longlink := services.GetLongLink(c.Input.Param(":link"))

	c.Redirect(302, longlink)
}

func RedirectQuery(c *context.Context) {
	c.Redirect(302, "/link/query")
}
